//
//  RylbVC.swift
//  Auscultation
//
//  Created by 来 on 2020/12/9.
//

import UIKit

class RylbVC: BaseVC {
    
    var type: String = ""
    
    var sample: [[String: String]]?
    
    var collectionView: UICollectionView!
    
    var selectRy: [Int] = []
    
    var dataArray: [[String: Any]] = []
    var pageNum: Int = 1
    var pageSize: Int = 10
    var keyWord: String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(loadData))
        collectionView.mj_footer = MJRefreshAutoNormalFooter.init(refreshingTarget: self, refreshingAction: #selector(loadMoreData))
        loadData()
    }
    
    // 数据刷新
    @objc func loadData() {
        pageNum = 1
        dataArray.removeAll()
        loadMoreData()
    }
    @objc func loadMoreData() {
        var paramet: [String: Any] = [:]
        if type == "标注样本" {
            paramet = [
                "keyWord": keyWord,
                "pageNo": pageNum.description,
                "pageSize": pageSize.description,
                "roleIds": [
                    "3124297098854400",
                    "3124295500824576"
                ],
                "hospitalId": EWEUser.lgf.hospitalId ?? "",
                "isDeleted": 1,
                "status": 2,
                "scope": 2
            ]
        } else if type == "审核样本" {
            paramet = [
                "keyWord": keyWord,
                "pageNo": pageNum.description,
                "pageSize": pageSize.description,
                "roleIds": [
                    "3124297241460736",
                    "3124295500824576"
                ],
                "hospitalId": EWEUser.lgf.hospitalId ?? "",
                "isDeleted": 1,
                "status": 2,
                "scope": 2
            ]
        }
        EWERequest.lgf("user", paramet, .get) { [weak self] (data) in
            let result = (data["result"] as? [[String: Any]]) ?? []
            if result.count > 0 {
                self?.dataArray += result
                self?.pageNum += 1
            }
            self?.collectionView.reloadData()
            self?.endRefreshing()
            if result.count == 0 {
                self?.collectionView.mj_footer?.endRefreshingWithNoMoreData()
            }
        } _: { [weak self] (error) in
            SVProgressHUD.showError(error)
            self?.endRefreshing()
        }
    }
    func endRefreshing() {
        self.collectionView.mj_header?.endRefreshing()
        self.collectionView.mj_footer?.endRefreshing()
    }
    
    // 添加
    @objc func wancheng(_ sender: UIButton) {
        add()
    }
    
    func add() {
        let alertVC = UIAlertController.init(title: nil, message: "确定添加吗", preferredStyle: .alert)
        alertVC.addAction(UIAlertAction.init(title: "确定", style: .default, handler: { [weak self] (action) in
            var labelUsers: [[String: String]] = []
            self?.selectRy.forEach { (index) in
                labelUsers.append(["userId": (self?.dataArray[index]["id"] as? String) ?? ""])
            }
            var paramet: [String: Any] = [:]
            var method = ""
            if self?.type == "标注样本" {
                if labelUsers.count != 2 {
                    SVProgressHUD.showError("标注人员数量须为2个")
                    return
                }
                paramet = [
                    "hospitalId": EWEUser.lgf.hospitalId ?? "",
                    "sample": self?.sample ?? [],
                    "labelUsers": labelUsers,
                    "expiryDay": "7",
                    "labelStatus": "0"
                ]
                method = "label"
            } else if self?.type == "审核样本" {
                paramet = [
                    "hospitalId": EWEUser.lgf.hospitalId ?? "",
                    "sample": self?.sample ?? [],
                    "userId": labelUsers.first?["userId"] ?? "",
                    "type": "20",
                    "labelUsers": [],
                ]
                method = "audit"
            }
            EWERequest.lgf(method, paramet, .post, JSONEncoding.default) { [weak self] (data) in
                SVProgressHUD.showSuccess("派包成功")
                Timer.lgf_After(S: 0.5) {
                    if self?.type == "标注样本" {
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ReloadBzrwbVC"), object: nil)
                    } else {
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ReloadShrwbVC"), object: nil)
                    }
                    if (self?.navigationController?.viewControllers.count)! > 2 {
                        self?.navigationController?.popToViewController((self?.navigationController?.viewControllers[(self?.navigationController?.viewControllers.count)! - 3])!, animated: true)
                    }
                }
            } _: { (error) in
                SVProgressHUD.showError(error)
            }
        }))
        alertVC.addAction(UIAlertAction.init(title: "取消", style: .cancel, handler: { (action) in
            
        }))
        UIApplication.shared.keyWindow?.rootViewController?.present(alertVC, animated: true, completion: nil)
    }
    
}

extension RylbVC: UITextFieldDelegate {
    func textFieldDidEndEditing(_ textField: UITextField) {
        keyWord = textField.text ?? ""
        loadData()
    }
}

extension RylbVC : UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize  {
        return CGSize.init(width: UIDevice.lgf_ScreenW, height: 110)
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataArray.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.lgf_DequeueReusableCell(with: RylbCell.self, for: indexPath)
        cell.tx.lgf_setImage((dataArray[indexPath.item]["avatar"] as? String) ?? "")
        cell.mz.text = (dataArray[indexPath.item]["realName"] as? String) ?? ""
        cell.yy.text = ((dataArray[indexPath.item]["hospital"] as? [String: Any])?["hospitalName"] as? String) ?? ""
        cell.sj.text = (dataArray[indexPath.item]["phone"] as? String) ?? ""
        cell.zw.text = ((dataArray[indexPath.item]["role"] as? [String: Any])?["name"] as? String) ?? ""

        if selectRy.contains(indexPath.item) {
            cell.backgroundColor = UIColor.init(lgf_HexString: "FFC28A")?.withAlphaComponent(0.1)
        } else {
            cell.backgroundColor = UIColor.white
        }
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if self.type == "标注样本" {
            if selectRy.contains(indexPath.item) {
                selectRy.lgf_Remove(indexPath.item)
            } else {
                selectRy.append(indexPath.item)
            }
        } else {
            selectRy.removeAll()
            selectRy.append(indexPath.item)
        }
        collectionView.reloadData()
    }
}
